package com.maidada.codesharebackend.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.maidada.codesharebackend.common.PageResult;
import com.maidada.codesharebackend.common.ThrowUtils;
import com.maidada.codesharebackend.exception.GlobalErrorCode;
import com.maidada.codesharebackend.mapper.CodeMapper;
import com.maidada.codesharebackend.model.dto.code.CodeAddRequest;
import com.maidada.codesharebackend.model.dto.code.CodeQueryRequest;
import com.maidada.codesharebackend.model.dto.code.CodeUpdateRequest;
import com.maidada.codesharebackend.model.entity.Code;
import com.maidada.codesharebackend.model.entity.User;
import com.maidada.codesharebackend.model.vo.CodeVO;
import com.maidada.codesharebackend.service.CodeService;
import com.maidada.codesharebackend.service.UserService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 代码表 Service 实现类
 *
 * @author wulinxuan
 */
@Service
public class CodeServiceImpl extends ServiceImpl<CodeMapper, Code> implements CodeService {

    @Resource
    private UserService userService;

    @Override
    public Long addCode(CodeAddRequest codeAddRequest) {
        // 创建代码
        Code code = BeanUtil.copyProperties(codeAddRequest, Code.class);
        // 设置默认查看次数
        code.setViewCount(0);

        boolean result = this.save(code);
        ThrowUtils.throwIf(!result, GlobalErrorCode.OPERATION_ERROR, "新增代码失败");

        return code.getId();
    }

    @Override
    public Boolean deleteCode(Long id) {
        ThrowUtils.throwIf(id == null || id <= 0, GlobalErrorCode.PARAMS_ERROR, "代码id不能为空");

        // 校验代码是否存在
        Code code = this.getById(id);
        ThrowUtils.throwIf(code == null, GlobalErrorCode.DATA_NOT_FOUND_ERROR, "代码不存在");

        boolean result = this.removeById(id);
        ThrowUtils.throwIf(!result, GlobalErrorCode.OPERATION_ERROR, "删除代码失败");

        return true;
    }

    @Override
    public Boolean updateCode(CodeUpdateRequest codeUpdateRequest) {
        Long id = codeUpdateRequest.getId();
        ThrowUtils.throwIf(id == null || id <= 0, GlobalErrorCode.PARAMS_ERROR, "代码id不能为空");

        // 校验代码是否存在
        Code code = this.getById(id);
        ThrowUtils.throwIf(code == null, GlobalErrorCode.DATA_NOT_FOUND_ERROR, "代码不存在");

        // 更新代码
        Code updateCode = BeanUtil.copyProperties(codeUpdateRequest, Code.class);
        boolean result = this.updateById(updateCode);
        ThrowUtils.throwIf(!result, GlobalErrorCode.OPERATION_ERROR, "修改代码失败");

        return true;
    }

    @Override
    public PageResult<CodeVO> pageCode(CodeQueryRequest codeQueryRequest) {
        // 构建查询条件
        LambdaQueryWrapper<Code> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(codeQueryRequest.getId() != null, Code::getId, codeQueryRequest.getId())
                .like(StrUtil.isNotBlank(codeQueryRequest.getTitle()), Code::getTitle, codeQueryRequest.getTitle())
                .like(StrUtil.isNotBlank(codeQueryRequest.getTags()), Code::getTags, codeQueryRequest.getTags())
                .eq(codeQueryRequest.getCreator() != null, Code::getCreator, codeQueryRequest.getCreator())
                .orderByDesc(Code::getCreateTime);

        // 分页查询
        Page<Code> page = new Page<>(codeQueryRequest.getPageNo(), codeQueryRequest.getPageSize());
        Page<Code> codePage = this.page(page, wrapper);

        // 转换为VO，并截取代码内容为前500个字符
        List<CodeVO> codeVOList = codePage.getRecords().stream()
                .map(code -> {
                    CodeVO codeVO = BeanUtil.copyProperties(code, CodeVO.class);
                    // 截取代码内容为前500个字符
                    if (StrUtil.isNotBlank(codeVO.getContent()) && codeVO.getContent().length() > 500) {
                        codeVO.setContent(codeVO.getContent().substring(0, 500));
                    }
                    return codeVO;
                })
                .collect(Collectors.toList());

        return new PageResult<>(codeVOList, codePage.getTotal());
    }

    @Override
    public CodeVO getCodeById(Long id) {
        ThrowUtils.throwIf(id == null || id <= 0, GlobalErrorCode.PARAMS_ERROR, "代码id不能为空");

        Code code = this.getById(id);
        ThrowUtils.throwIf(code == null, GlobalErrorCode.DATA_NOT_FOUND_ERROR, "代码不存在");

        CodeVO codeVO = BeanUtil.copyProperties(code, CodeVO.class);

        // 获取创建人昵称
        if (code.getCreator() != null) {
            User creator = userService.getById(code.getCreator());
            if (creator != null) {
                codeVO.setCreatorNickname(creator.getNickname());
            }
        }

        // 如果更新时间为空或等于创建时间，则不返回更新时间
        if (code.getUpdateTime() == null || code.getUpdateTime().equals(code.getCreateTime())) {
            codeVO.setUpdateTime(null);
        }

        return codeVO;
    }
}

